package com.ruoyi.web.controller.epidemic;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.epidemic.domain.*;
import com.ruoyi.epidemic.service.*;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 疫情防控信息收集Controller
 *
 * @author ruoyi
 * @date 2022-04-04
 */
@Controller
@RequestMapping("/wxcp/epidemic/collect")
public class YqInfoCollectController extends BaseController {
    private String prefix = "epidemic/collect";
    //审核状态(0未审核, 1审核通过, 2审核不通过, 1000未审核正常, 1001未审核异常)
    private static final String UNDO_AUDIT = "0";
    private static final String AUDIT_YES = "1";
    private static final String AUDIT_NO = "2";
    private static final String UNDO_AUDIT_YES = "1000";
    private static final String UNDO_AUDIT_NO = "1001";
    //用户管理部门权限类型permission_type：权限分类 1-审核 2-查看, 3-管理员，其他无权限
    private static final Integer SELECT_PERMISSION_TYPE = 2;

    private static final String INTERNAL_PERSONNAL = "N";
    private static final String EXTERNAL_PERSONNAL = "Y";


    @Autowired
    private IYqInfoCollectService yqInfoCollectService;
    @Autowired
    private IsmsService smsService;
    @Autowired
    private IWxCpSysUserService wxCpSysUserService;


    @Autowired
    IEpidemicUserDeptService epidemicUserDeptService;

    @Autowired
    IEpidemicUserDeptBashService epidemicUserDeptBashService;

    @Autowired
    IEpidemicControlDeptService epidemicControlDeptService;

    @Autowired
    IWxCpUserService wxCpUserService;


    private static final DateTimeFormatter FORMAT_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");

    @RequiresPermissions("epidemic:collect:list")
    @GetMapping()
    public String collect( ModelMap map)
    {
    	 String belongDate= FORMAT_DATE.format(LocalDateTime.now());
    	 map.addAttribute("belongDate", belongDate);
        return prefix + "/collect";
    }

    @RequiredWxOauth2
    @GetMapping("check")
    public String check(HttpServletRequest request, @RequestParam(value = "deptId", required = false)String deptId)
    {
    	 HttpSession session = request.getSession();
         String userId = (String) session.getAttribute(Constants.USER_ID);
         String belongDate= FORMAT_DATE.format(LocalDateTime.now());
         YqInfoCollect yqInfoCollect= new YqInfoCollect();
         yqInfoCollect.setUserId(userId);
         yqInfoCollect.setBelongDate(belongDate);

        // 增加扫码绑定
        if(StringUtils.isNotEmpty(deptId)){
            epidemicUserDeptService.bindUserDeptBash(userId, deptId);
        }

        //可以用来判断是否在可填写的时间段内

        //根据用户和日期判断是否已经填写，分别跳转到add 或者  show（sho界面根据审核状态，是否显示修改按钮）

        List<YqInfoCollect> list = yqInfoCollectService.selectYqInfoCollectList(yqInfoCollect);
        if(list.size()>0) {
            return "redirect:/wxcp/epidemic/collect/show/"+list.get(0).getId();
        }

        if(StringUtils.isEmpty(deptId)){
            int i = yqInfoCollectService.checkDept(userId);
            if(i < 0){
                return "redirect:/common/deptError";
            }
        }

        return "redirect:/wxcp/epidemic/collect/add";
    }

    /**
     * 查询疫情防控信息收集列表
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(YqInfoCollect yqInfoCollect)
    {
        startPage();
        List<YqInfoCollect> list = yqInfoCollectService.selectYqInfoCollectList(yqInfoCollect);
        return getDataTable(list);
    }

    /**
     * 导出疫情防控信息收集列表
     */
    @RequiresPermissions("epidemic:collect:export")
    @Log(title = "疫情防控信息收集", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(YqInfoCollect yqInfoCollect)
    {
        List<YqInfoCollect> list = yqInfoCollectService.selectYqInfoCollectList(yqInfoCollect);
        ExcelUtil<YqInfoCollect> util = new ExcelUtil<YqInfoCollect>(YqInfoCollect.class);
        return util.exportExcel(list, "疫情防控信息收集数据");
    }

    /**
     * 新增疫情防控信息收集
     */
    @RequiredWxOauth2
    @GetMapping("/add")
    public String add(HttpServletRequest request, ModelMap map)
    {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        map.put("userId", userId);
        map.put("collectType", "00");
        map.put("userType", "00");
        String fillDept = yqInfoCollectService.getFillDept(userId);
        map.put("deptName", fillDept);
        return prefix + "/add";
    }

    /**
     * 新增保存疫情防控信息收集
     */
    @Log(title = "疫情防控信息收集", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(YqInfoCollect yqInfoCollect) {
        AjaxResult ajaxResult = new AjaxResult();
        //防止重提交
        if (yqInfoCollect != null && StrUtil.isNotEmpty(yqInfoCollect.getUserId())) {
            String belongDate= FORMAT_DATE.format(LocalDateTime.now());
            yqInfoCollect.setBelongDate(belongDate);
            List<YqInfoCollect> list = yqInfoCollectService.selectYqInfoCollectList(yqInfoCollect);
            if (CollUtil.isNotEmpty(list) && list.size() > 0) {
                return AjaxResult.warn(list.get(0).getId()+"");
            }
        }
        int i = yqInfoCollectService.insertYqInfo(yqInfoCollect);
        if(i == -1){
            ajaxResult = AjaxResult.error("请先维护用户所属填报部门");
        } else if(i > 0){
            List<String> userIds=yqInfoCollectService.getAuditUserByUserId(yqInfoCollect.getUserId());
            WxCpSysUser user=wxCpSysUserService.selectWxCpSysUserByUserId(yqInfoCollect.getUserId());
            String name="";
            if(user!=null) {
            	  name=user.getUserName();
            }
            for(String id:userIds) {
                try {
                    smsService.send(id, "", "", name+"提交了疫情防控收集表，请尽快审核！");
                    logger.info("填报成功，短信提醒完成");
                } catch (WxErrorException e) {
                    logger.info("填报成功，短信提醒失败");
                }
            }
            ajaxResult = AjaxResult.success("填报成功");
        }
        return ajaxResult;
    }

    /**
     * 修改疫情防控信息收集
     */
    @RequiredWxOauth2
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        YqInfoCollect yqInfoCollect = yqInfoCollectService.selectYqInfoCollectById(id);
        mmap.put("yqInfoCollect", yqInfoCollect);
        return prefix + "/edit";
    }
    @RequiredWxOauth2
    @GetMapping("/show/{id}")
    public String show(@PathVariable("id") Long id, ModelMap mmap)
    {
        YqInfoCollect yqInfoCollect = yqInfoCollectService.selectYqInfoCollectById(id);
        String auditByName = "";
        if (ObjectUtil.isNotNull(yqInfoCollect) && StrUtil.isNotEmpty(yqInfoCollect.getAduitBy())) {
            AuditUserDTO auditUserDTO = yqInfoCollectService.selectUserInfoFromWxCpUser(yqInfoCollect.getAduitBy());
            if (ObjectUtil.isNotNull(auditUserDTO)) {
                auditByName = auditUserDTO.getUserName();
            }
        }
        mmap.put("yqInfoCollect", yqInfoCollect);
        mmap.put("auditByName", auditByName);
        return prefix + "/show";
    }

    /**
     * 修改保存疫情防控信息收集
     */
    @RequiredWxOauth2
    @Log(title = "疫情防控信息收集", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(YqInfoCollect yqInfoCollect)
    {
        yqInfoCollect.setAduitStatus("0");
        return toAjax(yqInfoCollectService.updateYqInfoCollect(yqInfoCollect));
    }

    /**
     * 删除疫情防控信息收集
     */
    @RequiresPermissions("epidemic:collect:remove")
    @Log(title = "疫情防控信息收集", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(yqInfoCollectService.deleteYqInfoCollectByIds(ids));
    }

    ///////////////////疫情防控核查相关操作页面及接口开始部分//////////////////////

    /**
     * 数据审核导航页面
     *  进入后分：人员管理和审核操作页面
     */
    @RequiredWxOauth2
    @GetMapping("/aduit")
    public String aduit(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        logger.info("当前登录用户id========"+userId);
        List<Long> longs = yqInfoCollectService.checkAduit(userId);
        if(longs == null || longs.isEmpty()){
            return "redirect:/common/aduitError";
        }
        return prefix + "/aduitNav";
    }

    /**
     * 查询当前用户所管理的所有部门信息列表(审核权限的部门)
     * @param request
     * @return
     */
    @RequiredWxOauth2
    @GetMapping("/aduit/deptList")
    @ResponseBody
    public AjaxResult getDeptList(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        List<AuditUserDTO> deptList = yqInfoCollectService.getDeptListByUserId(userId);
        if (CollUtil.isNotEmpty(deptList)) {
            return AjaxResult.success(deptList);
        }
        return AjaxResult.success(null);
    }

    /**
     * 人员管理页面
     * @param request
     * @return
     */
    @RequiredWxOauth2
    @GetMapping("/userManage")
    public String userManage(HttpServletRequest request) {
        return prefix + "/user";
    }

    /**
     * 数据权限页面
     * @param request
     * @return
     */
    @RequiredWxOauth2
    @GetMapping("/userPermisson")
    public String userPermisson(HttpServletRequest request) {
        return prefix + "/permisson";
    }
    /**
     * 人员管理页面---添加功能
     * @param request
     * @return
     */
    @RequiredWxOauth2
    @GetMapping("/userManage/add/{deptId}")
    public String userManageAdd(@PathVariable("deptId") String deptId, HttpServletRequest request, ModelMap mmap) {
        String deptName = yqInfoCollectService.selectDeptNameByDeptId(deptId);
        //添加部门类型
        EpidemicControlDept epidemicControlDept = epidemicControlDeptService.selectEpidemicControlDeptByDeptId(Convert.toLong(deptId));
        if (epidemicControlDept != null) {
            mmap.put("deptId", deptId);
            mmap.put("deptName", deptName);
            if (INTERNAL_PERSONNAL.equalsIgnoreCase(epidemicControlDept.getOutside())) {
                return prefix + "/userAdd";
            } else if (EXTERNAL_PERSONNAL.equalsIgnoreCase(epidemicControlDept.getOutside())) {
                return prefix + "/userAddEx";
            }
        }
        return null;
    }

    /**
     * 人员管理页面---人员列表
     * @param request
     * @return
     */
    @RequiredWxOauth2
    @GetMapping("/userManage/list/{deptId}")
    @ResponseBody
    public AjaxResult userManageList(@PathVariable("deptId") String deptId, HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        //获取当前用户所管理的部门下的所有用户列表
        if ("-1".equals(deptId)) {
            deptId = null;
        }
        List<AuditUserDTO> list = yqInfoCollectService.getUserInfoListByDeptIds(userId, deptId);
        if (CollUtil.isNotEmpty(list)) {
            return AjaxResult.success(list);
        }
        return AjaxResult.success(null);
    }

    /**
     * 人员管理页面---人员删除操作
     * @return
     */
    @RequiredWxOauth2
    @GetMapping("/userManage/delete/{userId}")
    @ResponseBody
    public AjaxResult userManageDelete(@PathVariable("userId") String userId) {
//      从epidemic_user_dept_bash表中删除该成员
        yqInfoCollectService.deleteEpidemicUserDeptBashByUserId(userId);
        return AjaxResult.success();
    }

    /**
     * 根据员工工号查询该员工信息，包括用户名及用户所在部门
     * @return
     */
    @RequiredWxOauth2
    @PostMapping("/user/getUserInfoByJobNum")
    @ResponseBody
    public AjaxResult getUserInfoByJobNum(HttpServletRequest request){
        /**
         * 返回结果,<类型,数据>
         *     1、-1 查无此人
         *     2、 1 已在当前管理部门下
         *     3、 2 在新系统表中，但不在当前管理部门下，提示是否切换到当前管理部门下
         *     4、 3 在老系统表中，提示是否添加到当前系统
         */
        EpidemicUserDTO epidemicUserDTO = null;
        //当前新增用户工号，即用户id
        String curNewUserId =  request.getParameter("userJobNumVal");
        /**
         * 1\根据userId在epidemic_user_dept_bash表中查询数据，存在？判断对应的dept_id = curDeptId? 相等，提示当前用户管理的部门中包含该用户，该用户已在当前管理的部门下
         * 如果在其它部门下，则提示是否切换到当前部门下，同意则添加，否在不处理
         * 2、如果上述表中，不存在该用户，则从wx_cp_user中查询用户，不存在提示查无此人，否在将该用户+curDeptId添加到epidemic_user_dept_bash表中
         */
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        //获取当前新增用户的信息, 从epidemic_user_dept_bash表
        AuditUserDTO auditUserDTO = yqInfoCollectService.selectUserInfoFromEpidemicUserDeptBash(curNewUserId);
        if (ObjectUtil.isNull(auditUserDTO)) {
            //从wx_cp_user中查询当前新增用户
            AuditUserDTO auditUserDTOSrc = yqInfoCollectService.selectUserInfoFromWxCpUser(curNewUserId);
            if (ObjectUtil.isNull(auditUserDTOSrc)) {
                epidemicUserDTO = EpidemicUserDTO.builder().type("-1").auditUserDTO(null).build();//-1 查无此人
            } else {
                epidemicUserDTO = EpidemicUserDTO.builder().type("3").auditUserDTO(auditUserDTOSrc).build();//3 在老系统表中，提示是否添加到当前系统
            }
        } else {
            //获取当前管理员所管理的所有部门信息
            List<AuditUserDTO> deptList = yqInfoCollectService.getDeptListByUserId(userId);
            if (CollUtil.isNotEmpty(deptList)) {
                List<AuditUserDTO> filterList = deptList.stream().filter(s -> auditUserDTO.getDeptId().equals(s.getDeptId())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(filterList) && filterList.size() > 0) {
                    epidemicUserDTO = EpidemicUserDTO.builder().type("1").auditUserDTO(auditUserDTO).build();//1 已在当前管理部门下
                } else {
                    epidemicUserDTO = EpidemicUserDTO.builder().type("2").auditUserDTO(auditUserDTO).build();// 2 在新系统表中，但不在当前管理部门下，提示是否切换到当前管理部门下
                }
            }
        }
        return AjaxResult.success(epidemicUserDTO);
    }

    /**
     * 根据员工工号查询该员工信息，包括用户名及用户所在部门
     * @return
     */
    @RequiredWxOauth2
    @PostMapping("/user/addUserInfoByJobNum")
    @ResponseBody
    public AjaxResult addUserInfoByJobNum(HttpServletRequest request){
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        String curUserId =  request.getParameter("userJobNumVal");
        String curDeptId =  request.getParameter("curDeptId");
        String srcDeptName =  request.getParameter("srcDeptName");
        if (StrUtil.isNotEmpty(curUserId)) {
            //查询当前curUserId是否存在epidemic_user_dept_bash表中,存在则更新;不存在则新增
            EpidemicUserDeptBash epidemicUserDeptBash = epidemicUserDeptBashService.selectEpidemicUserDeptBashByUserId(curUserId);
            if (ObjectUtil.isNull(epidemicUserDeptBash)) {
                //新增
                epidemicUserDeptBash = new EpidemicUserDeptBash();
                epidemicUserDeptBash.setUserId(curUserId);
                epidemicUserDeptBash.setDeptId(Convert.toLong(curDeptId));
                epidemicUserDeptBash.setCreateBy(userId);
                epidemicUserDeptBash.setRemark("原部门:["+srcDeptName+"]");
                epidemicUserDeptBashService.insertEpidemicUserDeptBash(epidemicUserDeptBash);
            } else {
                //更新
                epidemicUserDeptBash.setDeptId(Convert.toLong(curDeptId));
                epidemicUserDeptBash.setUpdateBy(userId);
                epidemicUserDeptBash.setRemark("原部门:["+srcDeptName+"]");
                epidemicUserDeptBashService.updateEpidemicUserDeptBash(epidemicUserDeptBash);
            }
        }
        return AjaxResult.success();
    }


    /**
     * 根据用户名和手机号添加外部成员
     * @return
     */
    @RequiredWxOauth2
    @PostMapping("/user/addUserEx")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult addUserEx(HttpServletRequest request){
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        String curDeptId =  request.getParameter("deptId");
        String curUserName =  request.getParameter("userName");
        String curUserId =  request.getParameter("phonenumber");
        //手机号作为当前用户的工号
        if (StrUtil.isNotEmpty(curUserId)) {
            //查询当前curUserId是否存在epidemic_user_dept_bash表中,存在则更新;不存在则新增
            EpidemicUserDeptBash epidemicUserDeptBash = epidemicUserDeptBashService.selectEpidemicUserDeptBashByUserId(curUserId);
            if (ObjectUtil.isNull(epidemicUserDeptBash)) {
                //新增用户到基本信息到wx_cp_user表,首先判断该用户是否存在wx_cp_user表中，如果不存在则添加
                WxCpUser wxCpUser = wxCpUserService.selectWxCpUserByUserId(curUserId);
                if (ObjectUtil.isNull(wxCpUser)) {
                    wxCpUser = new WxCpUser();
                    wxCpUser.setUserId(curUserId);
                    wxCpUser.setLoginName(curUserName);
                    wxCpUser.setUserName(curUserName);
                    wxCpUser.setCreateBy(userId);
                    wxCpUser.setUserType("01");
                    wxCpUserService.insertWxCpUser(wxCpUser);
                }
                //新增用户到基本信息到wx_cp_sys_user表,首先判断该用户是否存在wx_cp_sys_user表中，如果不存在则添加
                WxCpSysUser wxCpSysUser = wxCpSysUserService.selectWxCpSysUserByUserId(curUserId);
                if (ObjectUtil.isNull(wxCpSysUser)) {
                    wxCpSysUser = new WxCpSysUser();
                    wxCpSysUser.setUserId(curUserId);
                    wxCpSysUser.setLoginName(curUserName);
                    wxCpSysUser.setUserName(curUserName);
                    wxCpSysUser.setCreateBy(userId);
                    wxCpSysUser.setUserType("01");
                    wxCpSysUserService.insertWxCpSysUser(wxCpSysUser);
                }
                //新增用户
                epidemicUserDeptBash = new EpidemicUserDeptBash();
                epidemicUserDeptBash.setUserId(curUserId);
                epidemicUserDeptBash.setDeptId(Convert.toLong(curDeptId));
                epidemicUserDeptBash.setCreateBy(userId);
                epidemicUserDeptBash.setRemark("委外用户类型");
                epidemicUserDeptBashService.insertEpidemicUserDeptBash(epidemicUserDeptBash);
            } else {
                //该用户已存在系统中，请不用重复添加
                return AjaxResult.warn("该用户已存在系统中,请不要重复添加");
            }
        }
        return AjaxResult.success();
    }

    /**
     * 审核操作页面:
     *      列表页面，包括已审核、未审核、未提交三个tab页面
     * @param request
     * @return
     */
    @RequiredWxOauth2
    @GetMapping("/checkManage")
    public String checkManage(HttpServletRequest request) {
        return prefix + "/aduit";
    }

    /**
     * 审核详情页面
     */
    @RequiredWxOauth2
    @GetMapping("/aduit/info/{id}")
    public String aduitInfo(@PathVariable("id") String id, ModelMap mmap) {
        //已审批、未审批,仅查询当天的数据
        String belongDate= FORMAT_DATE.format(LocalDateTime.now());
        YqInfoCollect yqInfoCollect = yqInfoCollectService.selectYqInfoCollectById(Convert.toLong(id));
        String auditByName = "";
        if (ObjectUtil.isNotNull(yqInfoCollect) && StrUtil.isNotEmpty(yqInfoCollect.getAduitBy())) {
            AuditUserDTO auditUserDTO = yqInfoCollectService.selectUserInfoFromWxCpUser(yqInfoCollect.getAduitBy());
            if (ObjectUtil.isNotNull(auditUserDTO)) {
                auditByName = auditUserDTO.getUserName();
            }
        }
        mmap.put("yqInfoCollect", yqInfoCollect);
        mmap.put("auditByName", auditByName);
        return prefix + "/aduitInfo";
    }

    /**
     * 审核处理页面
     * @param
     * @return
     */
    @RequiredWxOauth2
    @GetMapping("/aduit/handle/{id}")
    public String aduitHandle(@PathVariable("id") String id, ModelMap mmap){
        //已审批、未审批,仅查询当天的数据
        String belongDate= FORMAT_DATE.format(LocalDateTime.now());
        YqInfoCollect yqInfoCollect = yqInfoCollectService.selectYqInfoCollectById(Convert.toLong(id));
        mmap.put("yqInfoCollect", yqInfoCollect);
        return prefix + "/aduitHandle";
    }

    /**
     * 获取疫情收集信息列表，三个Tab页面的数据
     */
    @RequiredWxOauth2
    @PostMapping("/aduit/getYqCollectInfo")
    @ResponseBody
    public AjaxResult getYqCollectInfo(HttpServletRequest request) {
        String deptId =  request.getParameter("deptId");
        String userHsStatus =  request.getParameter("userHsStatus");
        String auditStatusRadioValue =  request.getParameter("auditStatusRadioValue");
        if ("-1".equals(deptId) || StrUtil.isEmpty(deptId)) {
            deptId = null;
        }
        Map<String, List<AuditUserDTO>> resultMap = new HashMap<>();
        List<AuditUserDTO> auditedUserlist = new ArrayList<>();
        List<AuditUserDTO> unauditUserlist = new ArrayList<>();
        List<AuditUserDTO> unsubmitUserlist = new ArrayList<>();
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        /**
         * 1、已审批、未审批：从epidemic_user_dept用户部门权限表中查询该用户所管理的所有部门，如果为空，说明当前用户无审批权限
         * 否则根据从epidemic_user_dept中查询出该用户所管理的部门，然后根据查询到的部门dept_id列表从yq_info_collect表中查询所对应的用户信息，
         * 分类人员信息aduit_status审核状态(0未审核, 1已审批)
         * 2、未提交：从epidemic_user_dept用户部门权限表中查询该用户所管理的所有部门，根据部门dept_id列表从epidemic_user_dept_bash中查询部门所对应的所有用户，
         * 减去第一部分获取的所有用户id,即为未提交的用户
         */
        if (StrUtil.isNotEmpty(userId)) {
            //已审批、未审批,仅查询当天的数据
            String belongDate= FORMAT_DATE.format(LocalDateTime.now());
            List<AuditUserDTO> auditUserlist = yqInfoCollectService.getAuditUserList(userId, deptId, belongDate);
            if (CollUtil.isNotEmpty(auditUserlist)) {
                if (StrUtil.isNotEmpty(userHsStatus) && (UNDO_AUDIT_YES.equals(userHsStatus) || UNDO_AUDIT_NO.equals(userHsStatus))) {
                    unauditUserlist = auditUserlist.stream().filter(item ->
                            (!AUDIT_YES.equals(item.getAuditStatus()) && !AUDIT_NO.equals(item.getAuditStatus()) && userHsStatus.equals(item.getAuditStatus()))).collect(Collectors.toList());
                } else {
                    unauditUserlist = auditUserlist.stream().filter(item -> (!AUDIT_YES.equals(item.getAuditStatus()) && !AUDIT_NO.equals(item.getAuditStatus()))).collect(Collectors.toList());
                }
            }
            if (CollUtil.isNotEmpty(auditUserlist)) {
                if (StrUtil.isNotEmpty(auditStatusRadioValue)) {
                    auditedUserlist = auditUserlist.stream().filter(item -> (AUDIT_YES.equals(item.getAuditStatus()) || AUDIT_NO.equals(item.getAuditStatus()))
                            && auditStatusRadioValue.equals(item.getAuditStatus())).collect(Collectors.toList());
                } else {
                    auditedUserlist = auditUserlist.stream().filter(item -> (AUDIT_YES.equals(item.getAuditStatus()) || AUDIT_NO.equals(item.getAuditStatus()))).collect(Collectors.toList());
                }
            }
            //未提交
            List<String> auditUserIds = yqInfoCollectService.getAuditUserIdList(userId, deptId, belongDate);
            List<String> allUserIds = yqInfoCollectService.getUserIdListByDeptIds(userId, deptId);
            List<String> unsubmitUserIds = CollectionUtil.subtractToList(allUserIds, auditUserIds);
            if (CollUtil.isNotEmpty(unsubmitUserIds)) {
                unsubmitUserlist = yqInfoCollectService.getUnsubmitUserList(unsubmitUserIds);
            }
        }
        resultMap.put("audited", auditedUserlist);
        resultMap.put("unaudit", unauditUserlist);
        resultMap.put("unsubmit", unsubmitUserlist);
        return AjaxResult.success(resultMap);
    }

    /**
     * 审核提交操作
     */
    @RequiredWxOauth2
    @PostMapping("/aduit/auditOperate")
    @ResponseBody
    public AjaxResult auditOperate(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        String id = request.getParameter("id");
        String auditOperate = request.getParameter("auditOperate");
        YqInfoCollect yqInfoCollect = yqInfoCollectService.selectYqInfoCollectById(Convert.toLong(id));
        yqInfoCollect.setAduitStatus(auditOperate);
        yqInfoCollect.setAduitTime(new Date());
        yqInfoCollect.setAduitBy(userId);
        int result = yqInfoCollectService.updateYqInfoCollect(yqInfoCollect);
        String curAuditedUserId= yqInfoCollect.getUserId();
        String smsInfo = "";
        if(AUDIT_YES.equals(auditOperate)){
            smsInfo = "您的疫情防控收集表已审核通过!";
        }
        if(AUDIT_NO.equals(auditOperate)){
            smsInfo = "您的疫情防控收集表审核不通过，请重新填写!";
        }
        if(result>0) {
            String userType = epidemicUserDeptBashService.getUserTypeByUserId(curAuditedUserId);
            if(StrUtil.isNotEmpty(userType) && "N".equalsIgnoreCase(userType)){
                try {
                    smsService.send(curAuditedUserId, "", "", smsInfo);
                    logger.info("审核状态"+ (AUDIT_YES.equals(auditOperate) ? "通过": "不通过"));
                } catch (WxErrorException e) {
                    logger.info("审核状态"+ (AUDIT_YES.equals(auditOperate) ? "通过": "不通过")+"短信提醒失败");
                }
            }
            return AjaxResult.success();
        }else{
            logger.info("审核失败");
            return AjaxResult.error();
        }
    }

    /**
     * 一键处理操作
     * @param
     * @return
     */
    @RequiredWxOauth2
    @PostMapping("/aduit/oneKeyOperate")
    @ResponseBody
    public AjaxResult aduitHandle(String type,String deptId, HttpServletRequest request){
        if ("-1".equals(deptId) || StrUtil.isEmpty(deptId)) {
            deptId = null;
        }
        String userHsStatus =  request.getParameter("userHsStatus");
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        List<AuditUserDTO> unauditAuditUserDTOs = null;
        List<String> unauditUserIds = null;
        List<String> unsubmitUserIds = null;
        //已审批、未审批,仅查询当天的数据
        String belongDate= FORMAT_DATE.format(LocalDateTime.now());
        if (StrUtil.isNotEmpty(userId)) {
            List<AuditUserDTO> auditUserlist = yqInfoCollectService.getAuditUserList(userId, deptId, belongDate);
            if (StrUtil.isNotEmpty(userHsStatus) && (UNDO_AUDIT_YES.equals(userHsStatus) || UNDO_AUDIT_NO.equals(userHsStatus))) {
                unauditAuditUserDTOs = auditUserlist.stream().filter(item ->
                        (!AUDIT_YES.equals(item.getAuditStatus()) && !AUDIT_NO.equals(item.getAuditStatus()) && userHsStatus.equals(item.getAuditStatus()))).collect(Collectors.toList());
            } else {
                unauditAuditUserDTOs = auditUserlist.stream().filter(item -> (!AUDIT_YES.equals(item.getAuditStatus()) && !AUDIT_NO.equals(item.getAuditStatus()))).collect(Collectors.toList());
            }
            //未提交
            List<String> auditUserIds = yqInfoCollectService.getAuditUserIdList(userId, deptId, belongDate);
            List<String> allUserIds = yqInfoCollectService.getUserIdListByDeptIds(userId, deptId);
            unsubmitUserIds = CollectionUtil.subtractToList(allUserIds, auditUserIds);
        }
        if ("1".equals(type)) {//一键审核按钮
            //获取当前用户所管理的用户,未被审核的用户列表
            if (ObjectUtil.isNotNull(unauditAuditUserDTOs) && CollUtil.isNotEmpty(unauditAuditUserDTOs)) {
                logger.info("一键审核未被审核的用户列表"+unauditAuditUserDTOs.stream().map(m -> m.getUserName()).collect(Collectors.toList()));
                for (AuditUserDTO auditUserDTO:unauditAuditUserDTOs) {
                    //根据用户id查询当日未被审核的用户信息
                    YqInfoCollect yqInfoCollect = yqInfoCollectService.selectYqInfoCollectById(auditUserDTO.getId());
                    yqInfoCollect.setAduitStatus(AUDIT_YES);
                    yqInfoCollect.setAduitTime(new Date());
                    yqInfoCollect.setAduitBy(userId);
                    int result = yqInfoCollectService.updateYqInfoCollect(yqInfoCollect);
                    String smsInfo = "您的疫情防控收集表已审核通过!";
                    if(result>0 && StrUtil.isNotEmpty(yqInfoCollect.getUserId())) {
                        String userType = epidemicUserDeptBashService.getUserTypeByUserId(yqInfoCollect.getUserId());
                        if(StrUtil.isNotEmpty(userType) && "N".equalsIgnoreCase(userType)){
                            try {
                                smsService.send(yqInfoCollect.getUserId(), "", "", smsInfo);
                                logger.info("信息发送成功提醒: 审核通过");
                            } catch (WxErrorException e) {
                                logger.info("信息发送失败提醒: 审核通过");
                            }
                        }
                    }else{
                        logger.info("审核失败");
                    }
                }
            }
        } else if ("2".equals(type)) {//一键提醒按钮
            //获取当前用户所管理的用户,未提交核酸信息的用户列表
            if (ObjectUtil.isNotNull(unsubmitUserIds) && CollUtil.isNotEmpty(unsubmitUserIds)) {
                logger.info("一键提醒未提交核查报告的用户列表"+unsubmitUserIds);
                for (String curUserId:unsubmitUserIds) {
                    try {
                        if (StrUtil.isNotEmpty(curUserId)) {
                            //根据用户id查询用户类型，如果是内部人员则发短信
                            String userType = epidemicUserDeptBashService.getUserTypeByUserId(curUserId);
                            if(StrUtil.isNotEmpty(userType) && "N".equalsIgnoreCase(userType)){
                                logger.info(userType);
                                smsService.send(curUserId, "", "", "请尽快提交你今日的疫情防控核查收集表!");
                                logger.info("信息发送成功提醒: 尽快填写疫情防控核查收集表");
                            }
                        }
                    } catch (WxErrorException e) {
                        logger.info("信息发送失败提醒: 尽快填写疫情防控核查收集表");
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 获取当前登录用户所管理的部门树结构（查看权限）
     * @param request
     * @return
     */
    @RequiredWxOauth2
    @GetMapping("/userPermisson/deptTree")
    @ResponseBody
    public AjaxResult getDeptTree(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        //首先从epidemic_user_dept表中查询当前用户所具有查看权限的一级管理部门（permission_type：权限分类 1-审核 2-查看, 3-管理员，其他无权限）
        List<DeptTreeViewItem> rootDeptList = yqInfoCollectService.getUserDeptListByPermType(userId, SELECT_PERMISSION_TYPE);
        //查询当前系统中所有有效的管理部门数据
        List<DeptTreeViewItem> allDeptList = yqInfoCollectService.getAllDeptListFromControlDept();
        //以rootDeptList为起点递归子查询allDeptList从而形成树结构
        if (CollUtil.isNotEmpty(rootDeptList)) {
            rootDeptList.forEach(item -> {
                List<DeptTreeViewItem> childList = getChildItem(item.getDeptId(), allDeptList);
                item.setNodes(childList);
            });
            return AjaxResult.success(rootDeptList);
        } else {
            return AjaxResult.warn("当前你没有查看权限");
        }
    }

    private List<DeptTreeViewItem> getChildItem(Long id, List<DeptTreeViewItem> allDeptList) {
        //子部门
        List<DeptTreeViewItem> childList = new ArrayList<>();
        allDeptList.forEach(item -> {
            // 遍历所有节点，将所有的父id与传过来的根节点的id比较
            if (item.getParentDeptId().equals(id)) {
                childList.add(item);
            }
        });
        //递归
        childList.forEach(child -> child.setNodes(getChildItem(child.getDeptId(), allDeptList)));
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }

    ///////////////////////////疫情防控核查相关操作结束部分///////////////////////////////////


    /**
     * 审核页面
     */
//    @RequiredWxOauth2
//    @GetMapping("/aduit")
//    public String aduit(HttpServletRequest request, ModelMap map)
//    {
//        HttpSession session = request.getSession();
//        String userId = (String) session.getAttribute(Constants.USER_ID);
//        List<Long> longs = yqInfoCollectService.checkAduit(userId);
//        if(longs == null || longs.isEmpty()){
//            return "redirect:/common/aduitError";
//        }
//
//        return prefix + "/aduitList";
//    }

    @RequiredWxOauth2
    @GetMapping("/aduitEdit/{id}")
    public String aduitEdit(HttpServletRequest request, ModelMap map, @PathVariable("id") Long id)
    {
        YqInfoCollect yqInfoCollect = yqInfoCollectService.selectYqInfoCollectById(id);
        map.put("yqInfoCollect", yqInfoCollect);
        return prefix + "/aduitEdit";
    }

    /**
     *  审核选中信息
     */
    @RequiredWxOauth2
    @PostMapping( "/aduitInfos")
    @ResponseBody
    public AjaxResult aduitInfos(String ids)
    {
        return toAjax(yqInfoCollectService.aduitYqInfoCollectByIds(ids));
    }

    /**
     *  审核通过
     */
    @RequiredWxOauth2
    @PostMapping( "/aduitInfoOK")
    @ResponseBody
    public AjaxResult aduitInfoOK(String id)
    {
        YqInfoCollect yqInfoCollect = new YqInfoCollect();
        yqInfoCollect.setId(Long.valueOf(id));
        yqInfoCollect.setAduitStatus("1");
        int result=yqInfoCollectService.updateYqInfoCollect(yqInfoCollect);
        YqInfoCollect thisYqInfoCollect=yqInfoCollectService.selectYqInfoCollectById(Long.valueOf(id));
        String userId=thisYqInfoCollect.getUserId();
        if(result>0) {
            try {
                smsService.send(userId, "", "", "您的疫情防控收集表已审核通过！");
                logger.info("审核通过，短信提醒完成");
            } catch (WxErrorException e) {
                logger.info("审核通过，短信提醒失败");
            }
            return toAjax(1);
        }else{

            logger.info("审核失败");
            return toAjax(0);
        }

    }

    /**
     *  审核不通过
     */
    @RequiredWxOauth2
    @PostMapping( "/aduitInfoNO")
    @ResponseBody
    public AjaxResult aduitInfoNO(String id)
    {
        YqInfoCollect yqInfoCollect = new YqInfoCollect();
        yqInfoCollect.setId(Long.valueOf(id));
        yqInfoCollect.setAduitStatus("2");
        int result=yqInfoCollectService.updateYqInfoCollect(yqInfoCollect);
        YqInfoCollect thisYqInfoCollect=yqInfoCollectService.selectYqInfoCollectById(Long.valueOf(id));
        String userId=thisYqInfoCollect.getUserId();
        if(result>0) {
            try {
                smsService.send(userId, "", "", "您的疫情防控收集表审核不通过，请重新填写！");
                logger.info("审核不通过，短信提醒完成");
            } catch (WxErrorException e) {
                logger.info("审核不通过，短信提醒失败");
            }
            return toAjax(1);
        }else{
            logger.info("审核失败");
            return toAjax(0);
        }
    }

    /**
     *  审核所有查询的信息
     */
    @RequiredWxOauth2
    @PostMapping( "/aduitInfosAll")
    @ResponseBody
    public AjaxResult aduitInfosAll(YqInfoCollect yqInfoCollect)
    {
        return toAjax(yqInfoCollectService.aduitInfosAllSelect(yqInfoCollect));
    }

    /**
     * 查询疫情防控信息收集列表--待审核
     */
    @RequiredWxOauth2
    @PostMapping("/aduitList")
    @ResponseBody
    public TableDataInfo aduitList(HttpServletRequest request, YqInfoCollect yqInfoCollect)
    {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute(Constants.USER_ID);
        yqInfoCollect.setUserId(userId);

        String belongDate= FORMAT_DATE.format(LocalDateTime.now());
        yqInfoCollect.setBelongDate(belongDate);

        startPage();
        List<YqInfoCollect> list = yqInfoCollectService.selectYqInfoCollectListAduit(yqInfoCollect);
        return getDataTable(list);
    }


}
